/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * route.java
 *
 * Created on 26.11.2011, 15:46:35
 */
package view;

import data.model.Airport;
import data.model.Route;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import logic.business.DataEditor;
import logic.business.exceptions.ConstraintException;
import logic.business.exceptions.MalformedDataException;

/**
 *
 * @author zhenia
 */
public class NewRouteDialog extends javax.swing.JDialog {

    private String[] airportName;
    private DataEditor dataEditor;
    private List<Airport> airports;
    private String[] currentRoute = new String[6];
    private boolean result;

    /** Creates new form route */
    public NewRouteDialog(DataEditor de) {
        //   super(parent, true);
        dataEditor = de;
        airports = de.getAllAirports();
        airportName = new String[airports.size()];
        for (int i = 0; i < airportName.length; i++) {
            airportName[i] = airports.get(i).getName();
        }
        initComponents();
        departureAirports.setSelectedIndex(1);
        arrivalAirports.setSelectedIndex(1);
        System.out.println(departureAirports.getSelectedIndex());
        System.out.println(arrivalAirports.getSelectedIndex());
//        departureAirports.addActionListener(this);
//        arrivalAirports.addActionListener(this);

    }

    public String[] getCurrentRoute() {
        return currentRoute;
    }

    public void setCurrentRoute(String[] currentRoute) {
        this.currentRoute = currentRoute;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        ok = new javax.swing.JButton();
        cancel = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        departureAirports = new javax.swing.JComboBox();
        arrivalAirports = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("New Route");

        ok.setText("OK");
        ok.setName("ok"); // NOI18N
        ok.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okActionPerformed(evt);
            }
        });

        cancel.setText("Cancel");
        cancel.setName("cancel"); // NOI18N
        cancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelActionPerformed(evt);
            }
        });

        jLabel1.setText("Departure airport");
        jLabel1.setName("jLabel1"); // NOI18N

        jLabel2.setText("Arrival Airport");
        jLabel2.setName("jLabel2"); // NOI18N

        departureAirports.setModel(new javax.swing.DefaultComboBoxModel(airportName));
        departureAirports.setSelectedIndex(3);
        departureAirports.setName("departureAirports"); // NOI18N
        departureAirports.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                departureAirportsActionPerformed(evt);
            }
        });

        arrivalAirports.setModel(new javax.swing.DefaultComboBoxModel(airportName));
        arrivalAirports.setSelectedIndex(1);
        arrivalAirports.setName("arrivalAirports"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(ok)
                        .addGap(18, 18, 18)
                        .addComponent(cancel)
                        .addGap(36, 36, 36))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(82, 82, 82)
                                .addComponent(departureAirports, 0, 65, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 99, Short.MAX_VALUE)
                                .addComponent(arrivalAirports, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(159, 159, 159))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(departureAirports, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(arrivalAirports, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(210, 210, 210)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(ok)
                    .addComponent(cancel))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void okActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okActionPerformed


        Airport departureAirport = null;
        Airport arrivalAirport = null;
        for (Airport a : airports) {
            if (a.getName() == departureAirports.getSelectedItem()) {
                departureAirport = a;
            }
        }
        for (Airport a : airports) {
            if (a.getName() == arrivalAirports.getSelectedItem()) {
                arrivalAirport = a;
            }
        }

        try {
            dataEditor.addNewRoute(departureAirport.getName().toLowerCase() + "-" + arrivalAirport.getName().toLowerCase(), "0", "0", "0", departureAirport.getId(), arrivalAirport.getId());
        } catch (MalformedDataException ex) {
            JOptionPane.showMessageDialog(this,
                    "Arrival airport must be different from departure airport.",
                    "Warning",
                    JOptionPane.WARNING_MESSAGE);

        } catch (ConstraintException ex) {
            JOptionPane.showMessageDialog(this,
                    "Arrival airport must be different from departure airport.",
                    "Inane warning",
                    JOptionPane.WARNING_MESSAGE);
        }

       /* for (Route a : dataEditor.getAllRoutes()) {
            System.out.println(a.getId());
        }*/

        this.result = true;
        this.dispose();
    }//GEN-LAST:event_okActionPerformed

    private void cancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelActionPerformed

        this.result = false;
        this.dispose();
        // TODO add your handling code here:
    }//GEN-LAST:event_cancelActionPerformed

    public boolean execute() { // метод для "общения" с родительским окном
        this.setVisible(true); // прорисовать дочернее окно; в данном месте выполнение программы приостановится, ожидая окончания работы пользователя (в нашем случае - функции dispose())
        return this.result; // вернуть в качестве результата условное значение нажатой кнопки
    }

    public DataEditor getDataEditor() { // метод для "общения" с родительским окном
        //  this.setVisible(true); // прорисовать дочернее окно; в данном месте выполнение программы приостановится, ожидая окончания работы пользователя (в нашем случае - функции dispose())
        return this.dataEditor; // вернуть в качестве результата условное значение нажатой кнопки
    }

    private void departureAirportsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_departureAirportsActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_departureAirportsActionPerformed
    /**
     * @param args the command line arguments
     */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox arrivalAirports;
    private javax.swing.JButton cancel;
    private javax.swing.JComboBox departureAirports;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JButton ok;
    // End of variables declaration//GEN-END:variables
}
